package com.yzh.springboot_rbac.service.impl;

import com.yzh.springboot_rbac.entity.Menu;
import com.yzh.springboot_rbac.mapper.MenuMapper;
import com.yzh.springboot_rbac.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> selectAllMenu() {
        List<Menu> menus = menuMapper.selectAllMenu();
        HashMap<Integer, Menu> hashMap = new HashMap<>();
        for (Menu menu : menus) {
            hashMap.put(menu.getMenuId(), menu);
        }
        ArrayList<Menu> rootList = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId() == 0) {
                rootList.add(menu);
            } else {
                Menu parentNode = hashMap.get(menu.getParentId());
                if (parentNode != null) {
                    if (parentNode.getChildren() == null) {
                        parentNode.setChildren(new ArrayList<>());
                    }
                    parentNode.getChildren().add(menu);
                }
            }
        }
        return rootList;
    }

    @Override
    public Boolean isAddMenu(Menu menu) {
        List<Menu> menus = menuMapper.selectMenuByCondition(menu);
        if (menus.isEmpty()) {
            menuMapper.addMenu(menu);
            return true;
        } else {
            return false;//其实这个地方返回false有点问题，controller层接收不知道这个false是用户存在还是参数为空导致的，有待考究。
        }
    }

    @Override
    public List<Menu> selectMenuByCondition(Menu menu) {
        List<Menu> menus = menuMapper.selectMenuByCondition(menu);
        if (menus.isEmpty()) {
            return null;
        } else {
            return menus;
        }
    }

    @Override
    public Boolean deleteMenu(Menu menu) {
        int row = menuMapper.deleteMenu(menu);
        if (row > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Boolean isUpdateMenu(Menu menu) {
        int row = menuMapper.updateMenu(menu);
        if (row > 0) {
            return true;
        } else {
            return false;
        }
    }
}
